package com.zuozhj.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zuozhj.common.Result;
import com.zuozhj.entity.SysRole;
import com.zuozhj.entity.SysRoleMenu;
import com.zuozhj.service.ISysRoleMenuService;

import cn.hutool.core.util.StrUtil;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zuozhj
 * @since 2022-12-02
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseController {

    @Autowired
    ISysRoleMenuService sysRoleMenuService;


    @PreAuthorize("hasAuthority('sys:role:list')")
    @RequestMapping("/info/{id}")
    public Result info(@PathVariable(name = "id") Long id) {

        SysRole sysRole = sysRoleService.getById(id);

        List<Long> menuIds = sysRoleService.getMenuByRoleId(sysRole.getId());

        sysRole.setMenuIds(menuIds);

        return Result.success(sysRole);
    }


    @PreAuthorize("hasAuthority('sys:role:list')")
    @RequestMapping("/list")
    @SuppressWarnings("unchecked") 
    public Result list(String name) {

        Page<SysRole> roles = sysRoleService.page(getPage(), 
                new QueryWrapper<SysRole>().like(StrUtil.isNotBlank(name), "name", name)
            );

        return Result.success(roles);
    }

    @PreAuthorize("hasAuthority('sys:role:save')")
    @RequestMapping("/save")
    public Result save(@Validated @RequestBody SysRole sysRole) {

        sysRole.setCreatedAt(LocalDateTime.now());
        sysRole.setStatus(1);

        sysRoleService.save(sysRole);

        return Result.success(sysRole);
    }

    @PreAuthorize("hasAuthority('sys:role:update')")
    @RequestMapping("/update")
    public Result udpate(@Validated @RequestBody SysRole sysRole) {

        sysRole.setUpdatedAt(LocalDateTime.now());

        sysRoleService.updateById(sysRole);

        // 修改菜单需要同时删除菜单权限的缓存 
        sysUserService.clearUserAuthorityInfoByRoleId(sysRole.getId());

        return Result.success(sysRole);
    }

    @PreAuthorize("hasAuthority('sys:role:delete')")
    @RequestMapping("/delete")
    @Transactional          // 事务
    public Result delete(@RequestBody Long[] ids) {
        //批量删除
        sysRoleService.removeByIds(Arrays.asList(ids));

        // 删除中间表相关数据 SysRoleMenu, 数据库做了外键关联可以不写下面代码
        // sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("role_id", id));
        // sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", id));

        // 删除菜单需要同时删除菜单权限的缓存 
        Arrays.stream(ids).forEach(id -> {
            sysUserService.clearUserAuthorityInfoByRoleId(id);
        });


        return Result.success("");
    }

    @PreAuthorize("hasAuthority('sys:role:perm')")
    @RequestMapping("/perm/{roleId}")
    @Transactional
    public Result perm(@PathVariable(name = "roleId") Long roleId, @RequestBody Long[] menuIds ) {

        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
       

        Arrays.stream(menuIds).forEach(menuId -> {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(roleId);

            sysRoleMenus.add(roleMenu);
        });

        // 先删除中间表的数据再添加新数据
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id", roleId));
        sysRoleMenuService.saveBatch(sysRoleMenus);

         // 修改菜单需要同时删除菜单权限的缓存 
         sysUserService.clearUserAuthorityInfoByRoleId(roleId);

        return Result.success(menuIds);
    }

}
